/*
 * @Author: your name
 * @Date: 2022-02-10 23:04:45
 * @LastEditTime: 2022-02-10 23:27:00
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \ts\18泛型-类使用.ts
 */

// 1.类使用泛型-基础

class selectType<T> {
    constructor(private types:T[]) {
        
    }
    // 获取值，返回泛型定义的类型
    getType(type:number):T {
        return this.types[type]
    }

}
let type_1 = new selectType<string>(['c','c++','js']) // 定义泛型

console.log(type_1.getType(1))

// 2. 泛型中继承
// 继承接口
interface fxT {
    name:string
}
class fxTC <T extends fxT> {
    constructor(objArg:T) {
        
    }
}
// 要求每一个初始参数有name属性
let fxt_1 = new fxTC ({name:'kele'})


//3. 泛型约束
// 约束，指约束泛型能使用的类型  <T extends number|string |[] |object>
class fxYS <T extends number|string> {
    constructor(arg:T) {
        
    }
    // constructor(arg:booblean) { // 也可以单独指定类型
        
    // }
}
let fxys = new fxYS<number>(12)
let fxys1 = new fxYS('123')
// let fxys12 = new fxYS(true)

// 类型参数来约束
function getValue<T, U extends keyof T>(obj: T, key: U){
    return obj[key]
  }
  let aaa = {a: 1, b: 2, c: 3}
  getValue(aaa,"a");
//   getValue(a, "d");//error 提示 
  //Argument of type '"d"' is not assignable to parameter of type '"a" | "b" | "c" .

  